package com.it.service.impl;

import cn.hutool.core.util.IdUtil;
import com.it.bean.Document;
import com.it.mapper.DocumentMapper;
import com.it.service.DocumentService;
import com.it.utils.AppUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service("documentService")
@RequiredArgsConstructor
public class DocumentServiceImpl implements DocumentService {

    private final DocumentMapper documentMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Document upload(MultipartFile file) throws IOException {
        Document document = new Document();
        String uuid = IdUtil.simpleUUID();
        String filename = file.getOriginalFilename();
        String type = Objects.requireNonNull(filename).substring(filename.lastIndexOf("."));
        String name = uuid + type;
        byte[] data = file.getBytes();
        byte[] compress = AppUtils.compress(data);
        document.setSourceName(filename);
        document.setName(name);
        document.setUuid(uuid);
        document.setType(type);
        document.setSize(data.length);
        document.setUrl("/document/read/" + uuid);
        document.setData(compress);
        document.setDeleted(false);
        AppUtils.forSaveAudit(document);
        documentMapper.save(document);
        return document;
    }

    @Override
    public byte[] read(String uuid) throws IOException {
        Document condition = new Document();
        condition.setUuid(uuid);
        Document document = documentMapper.selectOne(condition);
        return AppUtils.decompress(document.getData(), document.getSize());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Document> uploads(MultipartFile[] files) throws IOException {
        List<Document> documents = new ArrayList<>();
        for (MultipartFile file : files) {
            Document document = upload(file);
            documents.add(document);
        }
        return documents;
    }
}
